import logging
from logging.handlers import RotatingFileHandler

from flask import Flask
from flask import g
from flask import render_template

from config import Config
from flask_sqlalchemy import SQLAlchemy
import redis
from flask_wtf.csrf import CSRFProtect,generate_csrf
from flask_session import Session
from config import config_map
from info.utils.common import do_index_class
# 设置日志的记录等级
logging.basicConfig(level=logging.DEBUG)
# 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
# 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
# 为刚创建的日志记录器设置日志记录格式
file_log_handler.setFormatter(formatter)
# 为全局的日志工具对象（flask app使用的）添加日志记录器
logging.getLogger().addHandler(file_log_handler)

db = SQLAlchemy()
redis_store = None  # type:redis.StrictRedis


def create_app(config_name):
    app = Flask(__name__)
    # 创建一个flask对象app
    config_class = config_map.get(config_name)
    # 获取到config_map字典中config_name的value
    app.config.from_object(Config)
    # 将配置信息传入flask对象中
    db.init_app(app)
    # 创建一个mysql数据库对象
    global redis_store
    redis_store = redis.StrictRedis(host=Config.REDIS_HOST, port=Config.REDIS_PORT,decode_responses=True)
    # 创建一个redis_store用来缓存之后可能会用到的验证码验证等信息
    CSRFProtect(app)
    # 添加CSRF验证保护
    @app.after_request
    def after_request(response):
        csrf_token = generate_csrf()
        response.set_cookie("csrf_token",csrf_token)
        return response

    from info.utils.common import user_login_data
    @app.errorhandler(404)
    @user_login_data
    def errorhandler_404(e):
        user = g.user
        data = {
            "user_info": user.to_dict() if user else None,
        }
        return render_template("news/404.html", data=data)



    app.add_template_filter(do_index_class,"indexClass")
    Session(app)
    # 将对象添加到session中
    from info.index import index_blue
    app.register_blueprint(index_blue)
    from info.passport import passport_blue
    app.register_blueprint(passport_blue)
    from info.news import news_blue
    app.register_blueprint(news_blue)
    from info.user import user_blue
    app.register_blueprint(user_blue)
    from info.admin import admin_blue
    app.register_blueprint(admin_blue)
    return app

